package com.sunchangpeng.wechat.mp.kf;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import com.sunchangpeng.wechat.core.WechatClient;
import com.sunchangpeng.wechat.mp.EndpointProvider;
import com.sunchangpeng.wechat.mp.MpAppSetting;
import com.sunchangpeng.wechat.mp.MpWechatClientFactory;
import lombok.Data;

import java.util.List;

import static com.sunchangpeng.wechat.core.utils.StringPool.MEDIA_NAME;


public class KFAccounts {
    private WechatClient wechatClient;

    public void setWechatClient(WechatClient wechatClient) {
        this.wechatClient = wechatClient;
    }

    public static KFAccounts with(MpAppSetting appSetting) {
        KFAccounts kfAccounts = new KFAccounts();
        kfAccounts.setWechatClient(MpWechatClientFactory.getInstance().with(appSetting));
        return kfAccounts;
    }

    public void add(String account, String nickName, String password) {
        String url = EndpointProvider.get("url.care.account.add");
        wechatClient.getTextWithToken(url, JSON.toJSONString(new JSONObject()
                .fluentPut("kf_account", account)
                .fluentPut("nickname", nickName)
                .fluentPut("password", password)));
    }

    public void update(String account, String nickName, String password) {
        String url = EndpointProvider.get("url.care.account.update");
        wechatClient.getTextWithToken(url, JSON.toJSONString(new JSONObject()
                .fluentPut("kf_account", account)
                .fluentPut("nickname", nickName)
                .fluentPut("password", password)));
    }

    public void delete(String account) {
        String url = EndpointProvider.get("url.care.account.delete");
        wechatClient.getTextWithToken(String.format(url, account));
    }


    public void uploadHeadImage(String account, String fileName, byte[] content) {
        String url = EndpointProvider.get("url.care.account.uploadhead");
        wechatClient.multiFormWithToken(String.format(url, account), MEDIA_NAME, fileName, content);
    }

    public List<KFAccount> kfList() {
        String url = EndpointProvider.get("url.care.account.list");
        String response = wechatClient.getTextWithToken(url);
        return JSON.parseObject(response, KFListResponse.class).getList();
    }

    public static class KFListResponse {
        @JSONField(name = "kf_list")
        private List<KFAccount> list;

        public List<KFAccount> getList() {
            return list;
        }

        public void setList(List<KFAccount> list) {
            this.list = list;
        }
    }

    @Data
    public static class KFAccount {
        @JSONField(name = "kf_id")
        private String id;

        @JSONField(name = "kf_account")
        private String account;

        @JSONField(name = "kf_nick")
        private String nickName;

        @JSONField(name = "kf_headimgurl")
        private String headImgUrl;
    }
}
